<template>
	<div class="login">
		<!-- LOGO -->
		<!-- from 表单 -->
		<el-form ref="form" :model="form" :rules="rules" class="from" label-width="60px">
			<!-- 头像 -->
			<el-form-item class="items avatar">
				<el-avatar
					:src="require('@/assets/顺大微生活.jpg')"
					:size="150"
					fit="cover"
					alt="logo"
				></el-avatar>
			</el-form-item>
			<!-- 输入框 -->
			<el-form-item label="账号" prop="username" class="items">
				<el-input
					v-model="form.username"
					prefix-icon="el-icon-user"
					clearable
					placeholder="手机号"
					validate-event
				></el-input>
			</el-form-item>
			<el-form-item label="密码" prop="password" class="items">
				<el-input
					v-model="form.password"
					type="password"
					prefix-icon="el-icon-lock"
					placeholder="密码"
					show-password
					clearable
					validate-event
				></el-input>
			</el-form-item>
			<!-- 控件 -->
			<el-form-item class="items">
				<el-button type="primary" @click="loginFn">登录</el-button>
				<el-button @click="resetFn">重置</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import { userLoginAPI } from '../api/user.js';
import { setToken, setUserId } from '../utils/localStorage.js';
export default {
	data() {
		return {
			// 表单数据
			form: {
				username: '13535337057',
				password: '123'
			},
			// 表单校验规则
			/*
				trigger - 触发校验时机
				required - 必填
				message - 错误提示信息
				pattern - 指定正则
			 */
			rules: {
				password: [
					{
						required: true,
						min: 3,
						max: 18,
						message: '密码需在3-18位之间',
						trigger: 'blur'
					}
				],
				username: [
					{
						required: true,
						pattern: /^1\d{10}$|^\d{5,6}/,
						message: '请输入正确的手机号码',
						trigger: 'blur'
					}
				]
			}
		};
	},
	methods: {
		// 登录事件
		loginFn() {
			// 表单规则校验
			/* 
				validate - ele表单校验方法
				valid - 所有规则校验的返回结果
			 */
			this.$refs.form.validate(async valid => {
				// 安全阻断
				if (!valid) return this.$message.error('请检查用户名和密码');

				const result = (await userLoginAPI(this.form)).data;
				console.log(result);
				// 安全阻断
				if (result.message !== '登录成功') return this.$message.error(result.message);
				setUserId(result.data.user.id);
				setToken(result.data.token);
				this.$message.success(result.message);
				this.$router.push('/');
			});
		},
		// 重置表单至默认状态（并非清空）
		resetFn() {
			this.$refs.form.resetFields();
			this.$message('重置表单');
		}
	}
};
</script>

<style lang="less" scoped>
.login {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	background-color: #f2f2f2;
	height: 100vh;
	width: 100vw;
}
.from {
	background-color: #ffffff;
	padding: 30px;
	border-radius: 10px;
	box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
	.items {
		margin-left: -15px;
		&:nth-child(1) {
			margin-left: 5px;
		}
		&:nth-child(4) {
			margin-left: 10px;
		}
	}
	.avatar {
	}
}
</style>
